# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from datetime import datetime

from django.http import  HttpResponseRedirect
from django.utils.http import urlquote

from apis import routes_api

from siteutils import escape_and_strip, requires_site_user, render_to_response, errorpage
from siteutils.language import _

def showallrides(request):
    pagesize = 50
    res = routes_api.get_all_rides(request, pagesize, order='-create_datetime')
    context = {"rides": res.get("rides", None),
               "end_cursor": res.get("end_cursor", ""),
               "subtitle": _("Rides"),
               "pagesize": pagesize}
    return render_to_response("allrides.html", context)


def showride(request, rideid):

    res = routes_api.get_ride_by_id(request, long(rideid))
    if res["status"] != "ok":
        return errorpage(res["message"])

    ride = res["ride"]
    context = {"ride": ride,
               "subtitle": "%s %s"%(_("Ride"),ride.name),
               }

    return render_to_response("show_ride.html", context)


@requires_site_user
def logride(request, routeid):
    message = request.GET.get("message", "")
    if message.find(u'\ufffd') >= 0:
        request.encoding = 'gb2312'
        message = request.GET.get("message", "")

    message = escape_and_strip(message)

    if request.method == "POST":
        try:
            select_route = long(escape_and_strip(request.POST.get("select_route", "")))
            select_bike = long(escape_and_strip(request.POST.get("select_bike", "")))

            starttime_utc = escape_and_strip(request.POST.get("starttime_utc", ""))
            starttime = datetime.strptime(starttime_utc, "%Y-%m-%d %H:%M")
            endtime_utc = escape_and_strip(request.POST.get("endtime_utc", ""))
            endtime = datetime.strptime(endtime_utc, "%Y-%m-%d %H:%M")

            time_duration = float(escape_and_strip(request.POST.get("time_duration", "")))

            ridename = escape_and_strip(request.POST.get("ridename", ""))
            weather = escape_and_strip(request.POST.get("weather", ""))
            effort = long(request.POST.get("effort", 0))
            #notes = escape_and_strip(request.POST.get("notes", ""))
            notes = request.POST.get("notes", "")

            result = routes_api.log_a_ride(request, select_route, select_bike,
                starttime, endtime, time_duration, name=ridename,
                weather=weather, effort=effort, notes=notes)

            if result["status"] == "error":
                raise Exception(result["message"])

        except Exception, e:
            from django.utils.encoding import force_unicode

            logging.exception("save ride error")
            msg = _("An Error occured: ") + force_unicode(str(e))
            return HttpResponseRedirect("/rides/logride/?message=%s" % (urlquote(msg)))

        return HttpResponseRedirect("/rides/%d" %result["ride"].id)

    try:
        context = {"message": message,
                   "subtitle": _("Log Ride"),}
        if routeid:
            context["route"] = routes_api.get_by_id(request, routeid).get("route", None)
    except:
        logging.exception("get route error")
        context = {"message": _("Can not get route ") + str(routeid)}

    return render_to_response("log_ride.html", context)


def main():
    pass

if __name__ == '__main__':
    main()
